/*
 * Copyright (c) 2019. ascend 版权所有禁止转载。
 */

package cn.edu.zua.demo17.entity;

import cn.edu.zua.demo17.base.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 说明：
 *
 * @author ascend
 * 2019/1/28 10:22
 */
@Entity
@Table(name = "test_user")
@Data
@Accessors(chain = true)
public class TestUserEntity extends BaseEntity implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    @Column(name = "user_name")
    private String userName;
    @Column(name = "user_password")
    private String userPassword;
    @Column(name = "age")
    private Integer age;
    @Column(name = "gmt_created")
    private LocalDateTime gmtCreated;
    @Column(name = "gmt_modified")
    private LocalDateTime gmtModified;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "test_user_role",
            joinColumns = {@JoinColumn(name = "user_id")},
            inverseJoinColumns = {@JoinColumn(name = "role_id")}
    )
    private List<TestRole> roleList;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> auths = new ArrayList<>();
        for(TestRole role : getRoleList()) {
            auths.add(new SimpleGrantedAuthority(role.getRoleFlag()));
        }
        return auths;
    }

    @Override
    public String getPassword() {
        return userPassword;
    }

    @Override
    public String getUsername() {
        return userName;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
